package com.kedacom.ctsp.authz.oauth2.configuration;

import com.kedacom.ctsp.authz.oauth2.core.JWTConfigProperties;
import com.kedacom.ctsp.authz.oauth2.util.RsaKeyHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;

/**
 * @remark:
 * @ClassName RsaKeyHelperConfiguration
 * @Author fenghaiju
 * @date 2018/6/29
 **/
@Configuration
@Slf4j
public class RsaKeyHelperConfiguration  implements CommandLineRunner {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private static final String REDIS_USER_PRI_KEY = "RBAC:AUTHZ:JWT:PRI";
    private static final String REDIS_USER_PUB_KEY = "RBAC:AUTHZ:JWT:PUB";

    @Autowired
    private KeyConfiguration keyConfiguration;
    @Autowired
    private JWTConfigProperties jwtConfigProperties;
    @Override
    public void run(String... strings) throws Exception {
        log.info(">>>>>>>>>>>>>>>服务启动执行，执行jwt密钥对生成操作<<<<<<<<<<<<<");
        if (redisTemplate.hasKey(REDIS_USER_PRI_KEY)&&redisTemplate.hasKey(REDIS_USER_PUB_KEY)) {
            keyConfiguration.setUserPriKey(RsaKeyHelper.toBytes(redisTemplate.opsForValue().get(REDIS_USER_PRI_KEY).toString()));
            keyConfiguration.setUserPubKey(RsaKeyHelper.toBytes(redisTemplate.opsForValue().get(REDIS_USER_PUB_KEY).toString()));

        } else {
            Map<String, byte[]> keyMap = RsaKeyHelper.getInstance().generateKey(jwtConfigProperties.getSigningKey());
            keyConfiguration.setUserPriKey(keyMap.get("pri"));
            keyConfiguration.setUserPubKey(keyMap.get("pub"));
            redisTemplate.opsForValue().set(REDIS_USER_PRI_KEY, RsaKeyHelper.toHexString(keyMap.get("pri")));
            redisTemplate.opsForValue().set(REDIS_USER_PUB_KEY, RsaKeyHelper.toHexString(keyMap.get("pub")));

        }
    }
}
